package cn.hy.preparelesson.module.business;


import cn.hy.preparelesson.common.constant.ProjectConstant;
import cn.hy.preparelesson.common.exception.MessageException;
import cn.hy.preparelesson.common.utils.DateUtils;
import cn.hy.preparelesson.common.utils.IdUtils;
import com.alibaba.fastjson.JSONObject;
import com.baidu.ueditor.ActionEnter;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * ueditor controller
 */
@RestController
@RequestMapping("/api/ue")
public class UeditorController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    private int count = 0;

    /**
     * ueditor 执行
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/operate")
    @ResponseBody
    public String ueditorConfig(HttpServletRequest request, HttpServletResponse response) {
        File targetFile = new File("yiyuan.ueditor.config_tmp.json");
        if (count == 0 || !targetFile.exists()) {
            if (targetFile.exists()) {
                targetFile.delete();
            }
            try (InputStream stream = getClass().getClassLoader().getResourceAsStream("ueditor.config.json")) {
                FileUtils.copyInputStreamToFile(stream, targetFile);
            } catch (IOException e) {
               throw new MessageException("获取配置文件失败！");
            }
            count ++;
        }
        String rootPath = request.getServletContext().getRealPath("/");
        return new ActionEnter(request, rootPath, "yiyuan.ueditor.config_tmp.json").exec();

    }

    /**
     * ueditor 上传图片
     * @return
     */
    @RequestMapping(value = "/operate", params = {"action=uploadimage"})
    @ResponseBody
    public String ueditorUploadImg(@RequestParam("upfile") MultipartFile file) {
        Map<String, Object> m = new HashMap<String, Object>();
        try (InputStream inputStream = file.getInputStream()) {
            String originFileName = file.getOriginalFilename();
            //存到服务器的绝对路径
            String fileExt = originFileName.substring(originFileName.lastIndexOf("."), originFileName.length());
            //存储到服务器的文件名
            String newFileName = IdUtils.newId() + fileExt;
            String dateDirPath = DateUtils.getDateDirPath();
            String newFilePath = ProjectConstant.ueditorUploadLocation + dateDirPath + "/" + newFileName;

            //客户端访问路径
            String visitPath = ProjectConstant.ueditorVisitPrefix + dateDirPath + "/";

            File toFile = new File(newFilePath);
            FileUtils.copyToFile(inputStream, toFile);
            m.put("path", ProjectConstant.hostName + visitPath);
            m.put("filename", newFileName);

            m.put("original", originFileName);
            m.put("name", newFileName);
            m.put("url", ProjectConstant.hostName + visitPath + newFileName);
            m.put("state", "SUCCESS");
            m.put("type", fileExt);
            m.put("size", file.getSize());
        } catch (Exception e) {
            logger.error("ueditor上传图片失败：", e);
            m.put("state", "上传失败！");
        }
        return JSONObject.toJSONString(m);
    }


    /**
     * ueditor 上传图片
     * @return
     */
    @RequestMapping(value = "/operate", params = {"action=uploadvideo"})
    @ResponseBody
    public String ueditorUploadVideo(@RequestParam("upfile") MultipartFile file) {
        Map<String, Object> m = new HashMap<String, Object>();
        try (InputStream inputStream = file.getInputStream()) {
            String originFileName = file.getOriginalFilename();
            //存到服务器的绝对路径
            String fileExt = originFileName.substring(originFileName.lastIndexOf("."), originFileName.length());
            //存储到服务器的文件名
            String newFileName = IdUtils.newId() + fileExt;
            String dateDirPath = DateUtils.getDateDirPath();
            String newFilePath = ProjectConstant.ueditorUploadLocation + dateDirPath + "/" + newFileName;

            //客户端访问路径
            String visitPath = ProjectConstant.ueditorVisitPrefix + dateDirPath + "/";

            File toFile = new File(newFilePath);
            FileUtils.copyToFile(inputStream, toFile);
            m.put("path", ProjectConstant.hostName + visitPath);
            m.put("filename", newFileName);

            m.put("original", originFileName);
            m.put("name", newFileName);
            m.put("url", ProjectConstant.hostName + visitPath + newFileName);
            m.put("state", "SUCCESS");
            m.put("type", fileExt);
            m.put("size", file.getSize());
        } catch (Exception e) {
            logger.error("ueditor上传视频失败：", e);
            m.put("state", "上传失败！");
        }
        return JSONObject.toJSONString(m);
    }
}
